<?php
/**
 * Nweb Editor
 *
 * This script is protected by copyright. Its use, copying, modification
 * and distribution without written consent of the author is prohibited.
 *
 * @category    source
 * @package     pl.nweb.editor.view
 * @subpackage  helper
 * @author      Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright   Copyright (c) 2012 Krzysztof Kardasz
 * @license     http://www.gnu.org/licenses/lgpl-3.0.txt  GNU Lesser General Public
 * @version     1.0 $Id$
 * @link        https://nweb-editor.googlecode.com
 * @link        http://editor.nweb.pl
 */

/**
 * Pomocnik widoku, skracanie tekstu
 *
 * @category    source
 * @package     pl.nweb.editor.view
 * @subpackage  helper
 * @author      Krzysztof Kardasz <krzysztof.kardasz@gmail.com>
 * @copyright   Copyright (c) 2012 Krzysztof Kardasz
 * @version     1.0 $Id$
 */
class Zend_View_Helper_Truncate  extends \Zend_View_Helper_Abstract
{
    /**
     * Skracanie tekstu
     *
     * @param string  $text tekst
     * @param integer $length makysmalna długość
     * @param string  $ending sposób zakończenia
     * @param boolean $force odcięcie sztywne do zadanej długości
     * @return string
     */
    public function truncate($text, $length, $ending = '...', $force = true)
    {
        if (mb_strlen($text, 'UTF-8') <= $length) {
            return $text;
        } else {
            $truncate = mb_substr ($text, 0, $length - mb_strlen($ending, 'UTF-8'), 'UTF-8');
            if (!$force) {
                $spacepos = mb_strrpos($truncate, ' ', 0, 'UTF-8');
                if (isset($spacepos)) {
                    return mb_substr($truncate, 0, $spacepos, 'UTF-8') . $ending;
                }
            }
            return $truncate . $ending;
        }
    }
}
